<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/18
 * Time: 11:33
 */

namespace app\api\controller;

use app\api\model\Member;
use think\Controller;
use Firebase\JWT\JWT;
use app\api\controller\Jpushmember;
use think\Db;

class Login extends Controller
{

    /**
     *登陆接口
     * */
    public function login()
    {

        $is_code = input('is_code');
        $username = input('username');
        $type = input('phone_type');
        $onlyId = input('only_id');

        if(!$username){
            $this->result('','-1','用户名未填写');
        }

        $member = new Member();
        $memberInfo = $member->where(['username' => $username])->find();
        if(count($memberInfo) == 0){
            $this->result('','-1','账号不存在','json',[]);
        }else{
            if($memberInfo['status'] == -1){
                $this->result('','-1','改账号被冻结','json',[]);
            }
            //登陆分为两种状态
            if($is_code == 1){
                $code = input('code');
                if(!$code){
                    $this->result('','-1','验证码未填写');
                }
                $cacheName = "login_mobile_".$username;
                $oldCode = cache($cacheName.'_code');
                $oldMobile = cache($cacheName);

                if($oldMobile !== $username){
                    $this->result('','-1','请先获取验证码','json',[]);
                }

                if($oldCode !== $code){
                    $this->result('','-1','验证码错误','json',[]);
                }else {
                    $token = $this->getToken($memberInfo['id']);
                    $data['token'] = $token;
                    if($memberInfo['phone_type'] != $type){
                        $data['phone_type'] = $type;
                    }
                    if($memberInfo['only_id'] != $onlyId){
                        $data['only_id'] = $onlyId;
                    }
                    $res = $member->where(['id' => $memberInfo['id']])->update($data);
                    if($res){
                        $this->result($data,'1','登陆成功','json',[]);
                    }else{
                        $this->result('','-1','登陆失败','json',[]);
                    }
                }
            }else{
                $password = input('password');
                if(!$password){
                    $this->result('','-1','密码未填写');
                }
                if(md5($password) == $memberInfo['password']){
                    $token = $this->getToken($memberInfo['id']);
                    $data['token'] = $token;
                    if($memberInfo['phone_type'] != $type){
                        $data['phone_type'] = $type;
                    }
                    if($memberInfo['only_id'] != $onlyId){
                        $data['only_id'] = $onlyId;
                    }
                    $res = $member->where(['id' => $memberInfo['id']])->update($data);
                    if($res){
                        $this->result($data,'1','登陆成功','json',[]);
                    }else{
                        $this->result('','-1','登陆失败','json',[]);
                    }
                }else{
                    $this->result('','-1','密码错误','json',[]);
                }
            }
        }

    }



    /**
     * 发送短信接口
     *
     * */
    public function registerSendSms()
    {
        $type = input('type');
        $mobile = input('mobile');
        if(!$mobile){
            $this->result('','-1','号码不得为空','json',[]);
        }

        $member = new Member();
        $count = $member->where(['mobile|username' => $mobile])->count();

        $code = rand('100000','999999');
        if($type == 1){
            if($count > 0){
                $this->result('','-1','该手机号已注册','json',[]);
            }
            $cacheName = "register_mobile_".$mobile;
            $content = "【先锋港湾】提醒您：您的注册验证码：".$code."，打死也不要告诉别人哦！！有效期10分钟";
        }else{
            if($count == 0){
                $this->result('','-1','该手机号未注册','json',[]);
            }
            $cacheName = "login_mobile_".$mobile;
            $content = "【先锋港湾】提醒您：您的登陆验证码：".$code."，打死也不要告诉别人哦！！有效期10分钟";
        }

        Cache($cacheName."_code",$code,['expire'=>600]);
        Cache($cacheName,$mobile,['expire'=>600]);

        $res = $member->sendMessage($mobile,$content,'');

        libxml_disable_entity_loader(true);
        //先把xml转换为simplexml对象，再把simplexml对象转换成 json，再将 json 转换成数组。
        $value_array = json_decode(json_encode(simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if($value_array['returnstatus'] == "Success"){
            $this->result('','1','发送成功','json',[]);
        }else{
            $this->result('','-1','发送失败','json',[]);
        }

    }


    /**
     * 注册接口
     *
     * */
    public function register()
    {

        $username = input('mobile');
        $password = input('password');
        $code = input('code');

        if(!$username || !$password || !$code){
            $this->result('','-1','数据未填写完整','json',[]);
        }
        $cacheName = "register_mobile_".$username;
        $oldCode = cache($cacheName.'_code');
        $oldMobile = cache($cacheName);

        if($oldMobile !== $username){
            $this->result('','-1','手机号有误','json',[]);
        }

        if($oldCode !== $code){
            $this->result('','-1','验证码错误','json',[]);
        }else{
            $member = new Member();

            $where['username|mobile'] = $username;
            $count = $member->where($where)->count();
            if($count > 0){
                $this->result('','-1','该账号已注册','json',[]);
            }else{
                $user = array(
                    'username' => $username,
                    'password' => md5($password),
                    'mobile' => $username,
                    'create_time' => time()
                );
                $res = $member->insertGetId($user);
                if($res){
                    //匹配党员信息
                    $partyMemberCount = Db::name('party_member')->where(['mobile' => $username])->count();
                    if($partyMemberCount > 0){
                        $updatePartyMember['user_id'] =$res;
                        Db::name('party_member')->where(['mobile' => $username])->update($updatePartyMember);
                    }
                    $this->result('','1','注册成功','json',[]);
                }else{
                    $this->result('','-1','注册失败','json',[]);
                }
            }

        }

    }


    /**
     * token获取方式
     * @param $user_id
     * @return mixed
     */
    public function getToken($user_id){
        $userInfo = Db::name('member')->where(['id'=>$user_id])->field('role_id,username')->find();
        $key = "huang";  //这里是自定义的一个随机字串，应该写在config文件中的，解密时也会用，相当    于加密中常用的 盐  salt
        $token = [
            "iss"=>"",  //签发者 可以为空
            "aud"=>"", //面象的用户，可以为空
            "iat" => time(), //签发时间
            "nbf" => time(), //在什么时候jwt开始生效  （这里表示生成100秒后才生效）
            "exp" => time()+365*60*60*24, //token 过期时间
            "uid" => $user_id, //记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
            "role_id" =>$userInfo['role_id'],
            "username" => $userInfo['username']
        ];
        $jwt = JWT::encode($token,$key,"HS256"); //根据参数生成了 token
        return $jwt;
    }


    /**
     * 执行推送任务
     */
    public function PushInfoMatter(){

        //引入极光推送SDK
        $alias = [1,2];
        $content = "555555";
//        vendor("JPush.MsgPush");
        //实例化极光推送类
        $pushmodel = new Jpushmember();
        //调用别名推送方法
        $res = $pushmodel -> sendNotifyAll($content);

        return $res;

    }


    public function test()
    {

        halt(1111);

    }


}